package com.shuqi.common.http;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.protocol.HttpContext;

import android.content.Context;

import com.shuqi.application.ShuqiApplication;
import com.shuqi.common.Config;
import com.shuqi.common.ConfigVersion;
/**
 * 书奇HTTP请求拦截器
 * 
 * @author li.li
 * @date 2014-06-24
 *
 */
public class ShuqiHttpRequestInterceptor implements HttpRequestInterceptor {

    @Override
    public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
        
        if (request != null) {
            Context ctx = ShuqiApplication.getContext();

            if (request instanceof HttpRequestBase) {
                
                // 根据网络类型重置host和端口
                HttpRequestBase requestBase = (HttpRequestBase) request;

                if (Config.getNetType(ctx) != null
                        && ("uniwap".equals(Config.getNetType(ctx))
                                || "cmwap".equals(Config.getNetType(ctx)) || "3gwap"
                                    .equals(Config.getNetType(ctx)))) {
                    
                    URI uri = requestBase.getURI();
                    String spec = "http://10.0.0.172:80" + uri.toURL().getFile();
                    try {
                        requestBase.setURI(new URI(spec));
                    } catch (URISyntaxException e) {
                        e.printStackTrace();
                    }
                    
                    //设置请求头信息
                    String host = uri.getHost();
                    requestBase.setHeader("X-Online-Host", host);
                    request.setHeader("IP-SRC",
                            "shuqi_" + Config.getNetType(ctx));
                    request.setHeader("aak", ConfigVersion.getAppApiKey());
                    request.setHeader("Accept-Encoding", "gzip");

                }

            }
        }
    }

}
